<?php

namespace App\Http\Controllers\API;

use App\Repositories\UsersRepository;
use App\User;
use App\ZL\Controllers\ApiBaseController;
use App\ZL\Library\ErrorCode;
use App\ZL\ORG\Xcx\Common;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;

class UsersController extends ApiBaseController
{
    protected $user;
    protected $store;
    protected $order;

    public function __construct(UsersRepository $usersRepository)
    {
        $this->user = $usersRepository;
    }

    public function userInfo()
    {
        $user = Auth::user();
        return responseZK(1,$user->toArray());
    }

    public function sendVerifyCode(Request $request)
    {
        $mobile_code = rand(100000,999999);
        $mobile = $request->tel;
        $mobile = $mobile?$mobile:$request->phone;
        $type = $request->type;
        if($type=='register' && $this->checkTel($mobile)){
            $res = responseZK(0,null,'此手机号已经注册');
        }elseif($type=='findPassword' && !$this->checkTel($mobile)){
            $res = responseZK(0,null,'此手机号没有注册');
        }else{
            //   阿里大鱼
            $send_result = sendVerifyCode($mobile, $mobile_code);
            if($send_result['status']==1){
                $res = responseZK(1,$mobile_code,'验证码发送成功');
                Cache::put('verify_tel_'.$mobile, $mobile_code, 300);
            }else{
                $res['status']=0;
                $res['msg']='验证码发送失败！';
                $value = Cache::pull('verify_tel_'.$mobile);
                $res = responseZK(0,null,'验证码发送太频繁');
            }
        }
        return $res;
    }

    public function setVerifyCode(Request $request)
    {
        $mobile = $request->tel;
        $mobile_code = $request->code;
        $mobile = $mobile?$mobile:$request->phone;
        if($this->checkTel($mobile)){
            $res = responseZK(0,null,'此手机号已经注册');
        }elseif($mobile_code!=Cache::get('verify_tel_'.$mobile)){
            $res = responseZK(0,null,'验证码错误');
        }else{
            $user = Auth::user();
            $user->phone = $mobile;
            $user->save();
            $res = responseZK(1,$mobile_code,'设置成功');
        }
        return $res;
    }

    public function checkTel($tel)
    {
        return User::where('phone',$tel)->first();
    }
}
